<template>
  <div class="page-container">
    <div
      class="main grid"
      :style="`--grid-template-columns: ${layout.col}; --grid-template-rows: ${layout.row}`"
    >
      <div
        class="section"
        v-for="(item, i) in layout.grids"
        :key="i"
        :style="`--grid-column: ${item.ax}; --grid-row: ${item.ay}`"
        :i="i"
      >
        <div
          class="section-item"
          v-for="(item2, ii) in pageConfig[i]"
          :key="ii"
        >
          <component
            ref="compId"
            :config="item2"
            :compKey="item2.componentKey"
            :children="item2.children"
            :data="list[item2.index]"
            :is="design[item2.componentKey]"
            @Form__Search="
              (comm, val) => {
                Form__Search(item2, comm, val);
              }
            "
            @Table_Modal__Open="
              (comm, btnInfo, row) => {
                Table_Modal__Open(item2, comm, btnInfo, row);
              }
            "
            @Table_Operate__Change="
              (comm, btnInfo, row) => {
                Table_Operate__Change(item2, comm, btnInfo, row);
              }
            "
          >
          </component>
        </div>
      </div>
    </div>

    <CommonModal
      ref="modalRef"
      :title="modal ? modal.title : ''"
      :data="modal ? modal.attrs : []"
      @confirm="Confirm_Modal"
      @close="Close_Modal"
    ></CommonModal>
  </div>
</template>
<script setup>
import { UserList } from "@/apis/user/list";
import { UserAdd } from "@/apis/user/add";
import { UserEdit } from "@/apis/user/edit";
import { UserDelete } from "@/apis/user/delete";

/**
 *  页面配置对象
 */

const pageConfig = ref({
  0: [
    {
      search: true,
      reset: true,
      layout: "inline",
      componentKey: "form",
      index: "0-e0dd32",
      children: [
        {
          componentKey: "input",
          index: "0-e0dd32-929cb2",
          attrs: {
            field: "name",
            label: "姓名",
            placeholder: "姓名",
            value: "",
            allowClear: true,
            componentKey: "input",
            type: "Input",
            index: "0-e0dd32-929cb2",
            isSelection: false,
            pagination: true,
            pageSize: "10",
            data: "user/list|user/add:post|user/edit:put|user/delete:delete",
            btns: ["add", "edit", "delete"],
            "title-l9nFsw": "姓名",
            "key-l9nFsw": "name",
            "slotName-l9nFsw": "",
            rules: [],
          },
        },
        {
          componentKey: "select",
          index: "0-e0dd32-d9cf77",
          attrs: {
            label: "状态",
            field: "status",
            placeholder: "状态",
            value: null,
            allowClear: true,
            optionsLabel: "label",
            optionsValue: "value",
            options: Filters.list("online"),
            required: false,
            componentKey: "select",
            type: "Select",
            rules: [],
            index: "0-e0dd32-d9cf77",
            filterObj: { online: { 0: "离线", 1: "在线" } },
          },
        },
      ],
      assign: "0-c1f3f9",
      apiUrl: "",
      rules: [],
    },
    {
      isSelection: false,
      pagination: {
        show: true,
        pageSize: "10",
        pageIndex: 1,
        showQuickJumper: true,
        showSizeChanger: true,
      },
      btns: ["add", "edit", "delete"],
      componentKey: "table",
      index: "0-c1f3f9",
      "title-lCtPAS": "姓名",
      "title-3UVap4": "手机号",
      "key-lCtPAS": "name",
      "key-3UVap4": "phone",
      "slotName-lCtPAS": "",
      "adb-lCtPAS": "",
      "slotName-3UVap4": "",
      "adb-3UVap4": "",
      getUserList: "UserList",
      modalTitle: "姓名",
      postUserAdd: "UserAdd",
      putUserEdit: "UserEdit",
      deleteUserDelete: "UserDelete",
      "title-UfXEU6": "操作",
      "key-UfXEU6": "operate",
      "slotName-UfXEU6": "",
      "adb-UfXEU6": "",
      apiGetUserList: UserList,
      apiPostUserAdd: UserAdd,
      apiPutUserEdit: UserEdit,
      apiDeleteUserDelete: UserDelete,
      rules: [],
      data: "/user/list|/user/add:post|/user/edit:put|/user/delete:delete",
    },
  ],
});

/**
 *  页面弹窗配置对象
 */

const modals = ref([
  {
    componentKey: "table",
    index: "0-c1f3f9",
    attrs: [
      {
        label: "手机号",
        field: "phone",
        type: "Input",
        allowClear: true,
        rules: [
          {
            type: "string",
            required: true,
            message: "手机号不能为空",
            trigger: "blur",
          },
        ],
        required: true,
      },
      {
        label: "姓名",
        field: "name",
        type: "Input",
        allowClear: true,
        rules: [],
      },
    ],
    title: "姓名",
  },
]);

/**
 *  layout格子配置对象
 */

const layout = ref({
  col: "repeat(24, minmax(0, 1fr))",
  row: "repeat(94, minmax(0, 1fr))",
  grids: [
    {
      x: 0,
      y: 0,
      w: 24,
      h: 95,
      i: 1,
      moved: false,
      ax: "1 / 25",
      ay: "1 / 95",
      nm: "gm1",
    },
  ],
});

// 定义一个可变的响应式变量 compId，用于存储组件的ID
const compId = ref(null);
// 定义一个可变的响应式变量 modalRef，用于存储模态框的引用
const modalRef = ref(null);
// 定义一个可变的响应式变量 list，用于存储列表数据
const list = ref({});
// 定义 emit 函数，用于触发自定义事件
const emit = defineEmits();
// 定义一个可变的响应式变量 currentIndex，用于存储当前模态框的索引
const currentIndex = ref("");

// 定义一个计算属性 modal，用于根据 currentIndex 查找对应的模态框对象
const modal = computed(() => {
  // 在 modals 数组中查找索引匹配的模态框对象
  const foundModal = modals.value.find((a) => a.index === currentIndex.value);
  // 如果找到了匹配的模态框对象，则返回它
  if (foundModal) {
    return foundModal;
  } else {
    // 如果没有找到匹配的模态框对象，则在控制台输出警告信息
    console.warn(
      "No matching modal found for the current index:",
      currentIndex.value,
    );
    // 可以选择返回 null 或者一个默认的 modal 对象
    return null; // 或者返回一个默认的 modal 对象
  }
});
/**
 * 触发事件并传递参数
 *
 * 此函数用于在特定事件上触发数据的更新或处理逻辑它接受三个参数：
 * 事件名(event)，第一个参数(val)，和第二个参数(val2)通过调用emit函数，
 * 将这些参数传递给监听该事件的订阅者或处理器
 *
 * @param {string} event - 事件名称，用于标识特定的事件
 * @param {*} val - 第一个事件参数，可以是任意类型
 * @param {*} val2 - 第二个事件参数，同样可以是任意类型
 */
const change = (event, val, val2) => {
  emit(event, val, val2);
};
/**
 * 获取组件
 */
const design = ref({});

Object.keys(Designer).forEach(async (key) => {
  const Des = await Designer[key]();
  design.value[key] = Des.default;
});

const confirmDelete = (comm, btnInfo, row) => {
  const val = getTableRowValue(comm, btnInfo, row);
  Modal.confirm({
    title: "提示",
    content: "确定删除吗？",
    onOk() {
      fetchTableApi("delete", val, comm.index);
    },
    onCancel() {},
  });
};
const getTableRowValue = (comm, btnInfo, row) => {
  if (btnInfo.key === "add") return {};
  const val = { ...row };
  const modal = modals.value.find((a) => a.index === comm.index);
  Object.keys(val).forEach((key) => {
    const attr = modal.attrs.find((a) => a.field === key);
    if (attr && attr.arr2str && val[key]) {
      val[key] = val[key].split(",");
    }
  });
  modal.row = val;
  return val;
};
const getTableApis = (comm, gs) => {
  const type = gs.substr(0, 1).toUpperCase() + gs.substr(1);
  const fn = Object.keys(comm).find((a) => a.indexOf(type) > -1);
  const nm = fn.substr(0, 1).toUpperCase() + fn.substr(1);
  return comm["api" + nm];
};
const fetchTableApi = async (gs, val, index) => {
  const Pcf = Object.values(pageConfig.value).flat();
  const Cp = Pcf.find((a) => a.index === index);
  const Api = getTableApis(Cp, gs);
  const { code, msg } = await Api(val);
  if (code === rescf.codeVal) {
    commId.value?.[Ci].fetchData();
    Close_Modal();
  } else {
    message.error(msg);
  }
  execApi();
};

const Form__Search = (item2, comm, val) => {
  const Pcf = Object.values(pageConfig.value).flat();
  let Ci = -1;
  if (comm.assign) {
    Ci = Pcf.findIndex((a) => a.index === comm.assign);
  }
  if (Ci > -1) {
    compId.value[Ci]?.fetchData();
  }
};
const Table_Modal__Open = (item2, comm, btnInfo, row) => {
  modal.apiType = btnInfo.key;
  Open_Modal(comm.index);
};
const Table_Operate__Change = (item2, comm, btnInfo, row) => {
  modal.apiType = btnInfo.key;
  if (btnInfo.key === "delete") {
    confirmDelete(comm, btnInfo, row);
  } else {
    Open_Modal(comm.index);
    const val = getTableRowValue(comm, btnInfo, row);
    nextTick(() => {
      modalRef.value?.setForm(val);
    });
  }
};
const Open_Modal = (index) => {
  currentIndex.value = index;
  modalRef.value?.showModal();
};

const Close_Modal = () => {
  modalRef.value?.resetFields();
  modalRef.value?.close();
};
const Confirm_Modal = async (val) => {
  const type = modal.apiType;
  const vals = Object.assign({}, val, modal.value.row);
  fetchTableApi(type, vals, modal.value.index);
};
</script>

<style lang="scss" scoped>
.flex {
  display: flex;
  flex-wrap: wrap;
}
.flex-1 {
  flex: 1;
}
.page-container {
  height: 100%;
  width: 100%;
  .main {
    margin: 0 auto;
    height: 100%;
    width: 100%;
    flex-direction: column;
    &.pc {
      width: 100%;
    }
    &.iphone {
      width: 480px;
    }
    &.grid {
      display: grid;
    }
  }
  .section {
    position: relative;
    width: 100%;
    grid-column: var(--grid-column);
    grid-row: var(--grid-row);
    min-width: 0px;
    display: flex;
    flex-direction: column;
    .section-item {
      &:last-child {
        flex: 1;
      }
    }
  }
  iframe {
    width: 100%;
    height: 100%;
  }
}
</style>
